﻿using Microsoft.Cloud.API.AzurePack.Authentication;
using System;
using System.Configuration;

namespace Microsoft.Cloud.API.AzurePack.Services
{
    /// <summary>
    /// authenictaion service
    /// </summary>
    public sealed class AuthService
    {
        // static holder for instance, need to use lambda to construct since constructor private
        private static readonly Lazy<AuthService> instance = new Lazy<AuthService>(() => new AuthService());

        private static string ADAuthEndpoint { get; set; }

        private static string ASPAuthEndpoint { get; set; }

        private static string ADFSAuthEndpoint { get; set; }

        private static string DomainName { get; set; }

        private static string AuthUserName { get; set; }

        private static string AuthUserPassword { get; set; }

        // private to prevent direct instantiation.
        private AuthService()
        {
            ADAuthEndpoint = ConfigurationManager.AppSettings["adAuthEndpoint"];
            ASPAuthEndpoint = ConfigurationManager.AppSettings["aspAuthEndpoint"];
            ADFSAuthEndpoint = ConfigurationManager.AppSettings["adfsAuthEndpoint"];
            DomainName = ConfigurationManager.AppSettings["domainName"];
            AuthUserName = ConfigurationManager.AppSettings["authUserName"];
            AuthUserPassword = ConfigurationManager.AppSettings["authUserPassword"];
        }

        // accessor for instance
        public static AuthService Instance
        {
            get
            {
                return instance.Value;
            }
        }

        /// <summary>
        /// get the security token for AD Authentication
        /// </summary>
        /// <returns></returns>
        public string PerformADAuth()
        {
            string securityToken = ADAuth.GetAuthToken(ADAuthEndpoint, DomainName, AuthUserName, AuthUserPassword, true);
            return securityToken;
        }

        /// <summary>
        /// get the security token for ASP Authentication
        /// </summary>
        /// <returns></returns>
        public string PerformASPAuth()
        {
            string securityToken = ASPAuth.GetASPToken(ASPAuthEndpoint, AuthUserName, AuthUserPassword);
            return securityToken;
        }

        /// <summary>
        /// get the security token for ADFS Authentication
        /// </summary>
        /// <returns></returns>
        public string PerformADFSAuth()
        {
            string securityToken = ADFSAuth.GetADFSToken(ADFSAuthEndpoint, AuthUserName, AuthUserPassword);
            return securityToken;
        }

        /// <summary>
        /// get the security token for ADFSASP Authentication
        /// </summary>
        /// <returns></returns>
        public string PerformADFSASPAuth()
        {
            string securityToken = ADFSASPAuth.GetADFSASPToken(ADFSAuthEndpoint, ASPAuthEndpoint, AuthUserName, AuthUserPassword);
            return securityToken;
        }
    }
}